package com.nnfe.fyd.feature.inquiryPrice;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nnfe.fyd.BusKey;
import com.nnfe.fyd.R;
import com.nnfe.fyd.ShareKey;
import com.nnfe.fyd.base.ActionBarFragment;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.bean.inquiry.AutoInquiry;
import com.nnfe.fyd.feature.login.LoginActivity;
import com.nnfe.fyd.http.CallbackImpl;
import com.nnfe.fyd.utils.DialogUtil;
import com.nnfe.fyd.utils.FragmentUtil;
import com.nnfe.fyd.utils.LogUtil;
import com.nnfe.fyd.utils.PopupViewUtil;
import com.nnfe.fyd.utils.SharePrefUtil;
import com.nnfe.fyd.utils.ToastUtil;
import com.nnfe.fyd.utils.common.DecimalTextWatcher;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/5/15.
 * <p/>
 * 描  述：自动询价
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class AutoInquiryPriceFragment extends ActionBarFragment {


    @Bind(R.id.tv_plan_for)
    TextView tvPlanFor;
    @Bind(R.id.rl_plan_for)
    RelativeLayout rlPlanFor;
    @Bind(R.id.et_area_name)
    TextView etAreaName;
    @Bind(R.id.et_live_area)
    EditText etLiveArea;
    @Bind(R.id.rl_house_area)
    RelativeLayout rlHouseArea;
    @Bind(R.id.tv_pledge)
    TextView tvPledge;
    @Bind(R.id.rl_pledge)
    RelativeLayout rlPledge;
    @Bind(R.id.rl_secound_sum)
    RelativeLayout rlSecoundSum;
    @Bind(R.id.et_secound_sum)
    EditText etSecoundSum;
    @Bind(R.id.btn_apply)
    Button btnApply;


    private ListViewAdapter listViewAdapter;
    private List<String> planForList = new ArrayList<>();
    private List<String> pledgeList = new ArrayList<>();

    // 住址类型，小区名称，建筑面积，抵押情况,二抵余额
    private String planFor, areaName, liveArea, pledge, pledgeString, secondSum="0";
    private String residentialareaName;
    private String roomAddress;


    @Override
    public Object getTitleString() {
        return "询价";
    }


    @Override
    public int getContentView() {
        return R.layout.fragment_auto_inquiryprice;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);

        initView();
        return rootView;
    }

    @Override
    protected void initView() {
        // 初始化规划用途
        if (planForList.size() == 0) {
            planForList.add("住宅");
            planForList.add("别墅");
        }

        // 初始化抵押情况
        if (pledgeList.size() == 0) {
            pledgeList.add("一抵");
            pledgeList.add("二抵");
        }

        rlSecoundSum.setVisibility(View.GONE);

        if (!TextUtils.isEmpty(planFor)) {
            tvPlanFor.setText(planFor);
        }
        if (!TextUtils.isEmpty(pledgeString)) {
            tvPledge.setText(pledgeString);
            if (pledgeString.equals("二抵")){
                rlSecoundSum.setVisibility(View.VISIBLE);
            }
        }

        listViewAdapter = new ListViewAdapter(mContext);

        etLiveArea.addTextChangedListener(new DecimalTextWatcher());
        etSecoundSum.addTextChangedListener(new DecimalTextWatcher());

    }

    @Override
    public void onResume() {
        super.onResume();
        AutoInquiryPriceActivity activity = (AutoInquiryPriceActivity) getActivity();
        if (!TextUtils.isEmpty(activity.getAreaName())) {
            etAreaName.setText(activity.getAreaName());
        }
        residentialareaName = activity.getResidentialareaNameAreaName();
        roomAddress = activity.getRoomAddress();
    }

    @Override
    public void initRightButton(Button rightButton) {
        super.initRightButton(rightButton);
        rightButton.setVisibility(View.VISIBLE);
        rightButton.setText("人工询价");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        ButterKnife.unbind(this);
    }

    @OnClick({R.id.btn_right, R.id.rl_plan_for, R.id.et_area_name,
            R.id.rl_house_area, R.id.rl_pledge, R.id.btn_apply})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_right:
                startActivity(new Intent(mContext, InquiryPriceActivity.class));
                break;
            case R.id.rl_plan_for:  // 住宅类型
                PopupViewUtil.showListPopupView(mContext, rlPlanFor, listViewAdapter, planForList, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        planFor = planForList.get(position);
                        tvPlanFor.setText(planFor);
                        PopupViewUtil.dismiss();
                    }
                });
                break;
            case R.id.et_area_name: // 输入小区名称
                FragmentUtil.replaceWithAddToBack(mContext, new SelectCommunityFragment());
                break;
            case R.id.rl_pledge:    // 抵押情况
                PopupViewUtil.showListPopupView(mContext, rlPledge, listViewAdapter, pledgeList, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        if (position == 0) {
                            rlSecoundSum.setVisibility(View.GONE);
                            etSecoundSum.setText("");
                        } else if (position == 1) {
                            rlSecoundSum.setVisibility(View.VISIBLE);
                        }
                        pledge = position  + 1 + "";
                        pledgeString = pledgeList.get(position);
                        tvPledge.setText(pledgeString);
                        PopupViewUtil.dismiss();
                    }
                });
                break;
            case R.id.btn_apply:
                if (SharePrefUtil.getBoolean(mContext, ShareKey.isLogin, false)) {
                    if (checkInquiry()) applyInquiry();
                } else {
                    LoginActivity.lauch(mContext, LoginActivity.TYPE_LOGIN);
                }
                break;
        }
    }

    /**
     * 验证是否可以询价
     *
     * @return
     */
    private boolean checkInquiry() {

        planFor = tvPlanFor.getText().toString().trim();
        areaName = etAreaName.getText().toString().trim();
        liveArea = etLiveArea.getText().toString().trim();
        secondSum = etSecoundSum.getText().toString().trim();

        if (TextUtils.isEmpty(planFor)) {
            ToastUtil.showToast("请选择住宅类型");
            return false;
        }

        if (TextUtils.isEmpty(areaName)) {
            ToastUtil.showToast("请输入小区名称！");
            return false;
        }

        // 建筑面积 小数点后两位   否则提示格不正确
        if (TextUtils.isEmpty(liveArea)) {
            ToastUtil.showToast("请输入建筑面积");
            return false;
        }


        if (TextUtils.isEmpty(pledge)) {
            ToastUtil.showToast("请选择抵押情况");
            return false;
        }

        if ("2".equals(pledge)) {
            if (TextUtils.isEmpty(secondSum)) {
                ToastUtil.showToast("一抵余额输入不能为空");
                return false;
            }
        }
        return true;
    }


    private void applyInquiry() {

        btnApply.setEnabled(false);
        DialogUtil.showLoadingDialog(mContext, "请求中");

        LogUtil.e("filter",residentialareaName);
        LogUtil.e("roomAddress",roomAddress);
        Call<HttpResult<AutoInquiry>> call = service.autoInquiry(SharePrefUtil.getString(mContext, ShareKey.UserId, ""),
                SharePrefUtil.getString(mContext,ShareKey.Token,""),
                roomAddress,
                residentialareaName, liveArea, planFor, pledge, secondSum, "app");
        call.enqueue(new CallbackImpl<AutoInquiry>() {
            @Override
            public void responseSuccess(Call<HttpResult<AutoInquiry>> call, Response<HttpResult<AutoInquiry>> response) {

                if (response.body().status == 0){
                    ToastUtil.showToast("您的申请已经提交成功");
                    EventBus.getDefault().post(BusKey.POST_inquiryReport);

                    // 跳页前先保存数据
                    AutoInquiryPriceActivity activity = (AutoInquiryPriceActivity) getActivity();
                    activity.setAutoInquiry(response.body().getData());

                    // 到询价结果页
                    FragmentUtil.replaceWithoutAddToBack(mContext, new InquiryResultFragment());
                    //mContext.finish();
                }
            }

            @Override
            protected void onRequestFinish() {
                super.onRequestFinish();
                if (!isDetached()){
                    btnApply.setEnabled(true);
                }
                DialogUtil.dismissLoadingDialog(mContext);
            }

            @Override
            public void onFailure(Call<HttpResult<AutoInquiry>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isDetached()){
                    ToastUtil.showToast("申请提交失败");
                }
            }
        });
    }

}
